package com.keyingbo.leran.pattern.proxy.mydynamic;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @Auther: KEYB
 * @Date: 2019-3-13 23:20
 * @Description:
 */
public class MyClassLoader extends ClassLoader {
    //获取MyClassLoader.class所在路径
    private  File classPathFile;
    private  Class targetClass;
    public MyClassLoader(Class clazz){
        classPathFile = new File(clazz.getResource("").getPath());
        targetClass = clazz;
    }
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String className = targetClass.getPackage().getName() + "." + name;
        File classFile = new File(classPathFile,name.replaceAll("\\.","/") + ".class");
        if(classFile.exists()){
            FileInputStream in = null;
            ByteArrayOutputStream out = null;
            try{
                in = new FileInputStream(classFile);
                out = new ByteArrayOutputStream();
                byte [] buff = new byte[1024];
                int len;
                while ((len = in.read(buff)) != -1){
                    out.write(buff,0,len);
                }
                return defineClass(className,out.toByteArray(),0,out.size());
            }catch (Exception e){
                e.printStackTrace();
            }
        } else{
            throw new ClassNotFoundException(name);
        }
        return  null;
    }

}
